<template>
  <div class="layout-page bg-#f8f9fe pt-32px">
    <div class="layout-page-inner box-border bg-#fff w-1328px py-70px">
      <h3 class="font-size-24px fw-500 text-center mb-57px">
        {{ isAdd ? "新增" : "编辑" }}需求信息
      </h3>
      <el-form
        class="apply-form w-60% mx-auto"
        ref="applyForm"
        :model="formData"
        :rules="rules"
        label-position="right"
        :label-width="130"
      >
        <el-form-item label="需求类型" prop="demandType">
          <el-select
            v-model="formData.demandType"
            placeholder="请选择需求类型"
            @change="typeChange"
          >
            <el-option
              v-for="option in SOURCE_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="需求标题" prop="demandTitle">
          <el-input
            v-model="formData.demandTitle"
            placeholder="请输入需求标题"
            :maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandName" v-if="formData.demandType===5">
          <el-input
              v-model="formData.brandName"
              placeholder="请输入品牌"
              :maxlength="20"
          ></el-input>
        </el-form-item>

        <el-form-item label="型号" prop="modelName" v-if="formData.demandType===5">
          <el-input
              v-model="formData.modelName"
              placeholder="请输入型号"
              :maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="需求说明" prop="demandDesc">
          <el-input
            type="textarea"
            v-model="formData.demandDesc"
            placeholder="请输入需求说明"
            :autoSize="{ minRows: 3 }"
            :maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="省市" prop="provinceArr">
          <ProvinceSelect
            v-model="formData.provinceArr"
            placeholder="请选择城市省市"
          />
        </el-form-item>
<!--        <el-form-item label="需求预算单位" prop="priceUnit">-->
<!--          <el-select v-model="formData.priceUnit" placeholder="请选择单位">-->
<!--            <el-option-->
<!--              v-for="option in unitOptionsList"-->
<!--              :key="option.value"-->
<!--              :value="option.value"-->
<!--              :label="option.label"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="需求预算（元）" prop="budgetPrice">
          <div class="flex w-full items-center">
            <el-input
              v-model.number="formData.budgetPrice"
              placeholder="请输入需求预算"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input
            v-model="formData.contactUser"
            placeholder="请输入联系人"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="contactUserMobile">
          <div class="flex w-full items-center">
            <el-input
              v-model="formData.contactUserMobile"
              placeholder="请输入联系电话"
              :maxlength="11"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="需求时间" prop="demandTime">
          <el-date-picker
            style="width: 60%"
            type="daterange"
            v-model="formData.demandTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="需求开始日期"
            end-placeholder="需求截止日期"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="需求有效时间" prop="deadTime">
          <el-date-picker
            style="width: 60%"
            type="date"
            v-model="formData.deadTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择截止时间"
          ></el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            class="mt-36px h-48px w-108px b-rd-0"
            :loading="confirmLoading"
            @click="handleSubmit"
            >确认提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { useLoading, useDict } from "@/hooks";
import { SOURCE_TYPE_OPTIONS, DICT_MAP } from "@/const";
import { useUserStore } from "@/store";

const route = useRoute();
const isAdd = computed(() => !route.query.id);
const router = useRouter();
const $api = inject("$api");
const applyForm = ref();
const { loading: confirmLoading, setLoading } = useLoading();

const { list: frameUnitOptions } = useDict(DICT_MAP.frame_price_unit);
const { list: bwUnitOptions } = useDict(DICT_MAP.bw_price_unit);
const { list: gpuUnitOptions } = useDict(DICT_MAP.gpu_price_unit);
const { list: goodsUnitOptions } = useDict(DICT_MAP.goods_price_unit);

const userStore = useUserStore();

const formData = ref({
  demandType: null,
  demandTitle: "",
  demandDesc: "",
  modelName:"",
  brandName:"",
  provinceArr: null,
  budgetPrice: null,
  demandTime: null,
  // deadTime: null,
  remark: "",
  contactUser: userStore.userInfo?.nickName,
  contactUserMobile: userStore.userInfo?.phonenumber,
  orderNum: 0,
  priceUnit: null,
});

const unitOptionsList = computed(() =>
  formData.value.demandType === 1
    ? frameUnitOptions.value
    : formData.value.demandType === 2
    ? bwUnitOptions.value
    : formData.value.demandType === 4
    ? gpuUnitOptions.value
    : formData.value.demandType === 5
    ? goodsUnitOptions.value
    : []
);

const typeChange = () => {
  formData.value.priceUnit = null;
};

watch(
  () => userStore.userInfo,
  (val) => {
    formData.value.contactUser = val.nickName;
    formData.value.contactUserMobile = val.phonenumber;
  }
);

const rules = reactive({
  demandType: [{ required: true, message: "请选择供应类型" }],
  demandTitle: [{ required: true, message: "请输入需求标题" }],
  demandDesc: [{ required: true, message: "请输入需求说明" }],
  modelName:[{ required: true, message: "请输入型号" }],
  brandName:[{ required: true, message: "请输入品牌" }],
  provinceArr: [{ required: true, type: "array", message: "请选择省市" }],
  budgetPrice: [
    { required: true, message: "请输入需求预算" },
    { type: "number", message: "请输入正确的需求预算类型" },
  ],
  demandTime: [{ required: true, type: "array", message: "请选择需求时间" }],
  // deadTime: [{ required: true, message: "请选择需求有效时间" }],
  contactUser: [{ required: true, message: "请输入联系人" }],
  contactUserMobile: [{ required: true, message: "请输入联系电话" }],
});

const handleSubmit = async () => {
  applyForm.value.validate(async (valid) => {
    if (!valid) return;
    setLoading(true);
    try {
      const submitData = toValue(formData);
      // 处理时间
      submitData.demandBegin = submitData.demandTime[0];
      submitData.demandEnd = submitData.demandTime[1];
      delete submitData.demandTime;
      // 处理省市
      [submitData.provinceName, submitData.cityName] = submitData.provinceArr;
      delete submitData.provinceArr;
      const apiName = isAdd.value ? "createDemand" : "updateDemand";
      await $api.supply[apiName](submitData);
      ElMessage.success(isAdd.value ? "创建成功" : "编辑成功");
      setTimeout(() => {
        router.push("/userCenter?active=demand");
      }, 500);
    } catch (e) {
      setLoading(false);
    }
  });
};
const getDetail = async (id) => {
  const { data } = await $api.supply.getDemandDetail(id);
  data.demandTime = [data.demandBegin, data.demandEnd];
  data.provinceArr = [data.provinceName, data.cityName];
  formData.value = data;
};

onMounted(() => {
  if (route.query.id) getDetail(route.query.id);
});
</script>
